package com.zaofan.utils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.TreeMap;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.http.util.TextUtils;

public class WebUtils {

	public static final String appSecret = "86c42d9dc49e31ded1936a71854c0fdfb67b8505";

	static {
		ConvertUtils.register(new DateTimeConverter(), java.util.Date.class);
	}
	
	public static String makeId() {
		return UUID.randomUUID().toString();
	}

	public static String formatDate(Date date) {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return df.format(date);
	}

	public static Date parseDate(String date) {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		try {
			return df.parse(date);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static String getBookNum() {
		return UUID.randomUUID().toString().substring(0, 32).replaceAll("-", "");
	}

	public static String getOrderId(Integer userId) {
		Date now = new Date();
		SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
		String temp = df.format(now);
		return "F" + temp + userId;
	}

	public static String makeDir(String realPath, String name) {
		int code = name.hashCode();
		int dir1 = code & 0xf;
		int dir2 = (code & 0xf0) >> 4;
		String dir = realPath + "/" + dir1 + "/" + dir2;
		File file = new File(dir);
		if (!file.exists()) {
			file.mkdirs();
		}
		return dir1 + "/" + dir2;
	}

	public static String getUUID() {
		return UUID.randomUUID().toString().substring(0, 10);
	}

	public static String makeFilePath(String filename, String realpath) {

		int hashcode = filename.hashCode();
		int dir1 = hashcode & 0xf;
		int dir2 = (hashcode & 0xf0) >> 4;
		String dir = realpath + "\\" + dir1 + "\\" + dir2;
		File file = new File(dir);
		if (!file.exists()) {
			file.mkdirs();
		}
		return dir;
	}

	public static String makeFilePath(String filename) {

		int hashcode = filename.hashCode();
		int dir1 = hashcode & 0xf;
		int dir2 = (hashcode & 0xf0) >> 4;
		String dir = "/" + dir1 + "/" + dir2;

		return dir;
	}

	@SuppressWarnings("unchecked")
	public static <T> T write2bean(HttpServletRequest request, Class<T> clazz) {

		try {
			Object obj = clazz.newInstance();
			Enumeration<String> enumeration = request.getParameterNames();
			while (enumeration.hasMoreElements()) {
				String name = enumeration.nextElement();
				Object value = request.getParameter(name);
				try {
					BeanUtils.setProperty(obj, name, value);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			return (T) obj;
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}

	}

	public final static String MD5(String s) {
		char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
		try {
			byte[] btInput = s.getBytes();
			MessageDigest mdInst = MessageDigest.getInstance("MD5");
			mdInst.update(btInput);
			byte[] md = mdInst.digest();
			int j = md.length;
			char str[] = new char[j * 2];
			int k = 0;
			for (int i = 0; i < j; i++) {
				byte byte0 = md[i];
				str[k++] = hexDigits[byte0 >>> 4 & 0xf];
				str[k++] = hexDigits[byte0 & 0xf];
			}
			return new String(str);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public static boolean isEmpty(Object object) {
		if (object == null) {
			return true;
		}
		if (object instanceof String) {
			if ("".equals(object)) {
				return true;
			}
		}
		return false;
	}

	public static boolean isMobileNO(String mobiles) {
		Pattern p = Pattern.compile("^((13[0-9])|(15[0-9])|(14[0-9])|(17[0-9])|(18[0-9]))\\d{8}$");
		Matcher m = p.matcher(mobiles);
		return m.matches();
	}

	public static boolean isEmail(String email) {
		String str = "^([a-zA-Z0-9]*[-_]?[a-zA-Z0-9]+)*@([a-zA-Z0-9]*[-_]?[a-zA-Z0-9]+)+[\\.][A-Za-z]{2,3}([\\.][A-Za-z]{2})?$";
		Pattern p = Pattern.compile(str);
		Matcher m = p.matcher(email);
		return m.matches();
	}

	public static String getRandonNum(int size) {
		String[] digits = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "0" };
		Random rnum = new Random(new Date().getTime());
		for (int i = 0; i < digits.length; i++) {
			int index = Math.abs(rnum.nextInt()) % 10;
			String tmpDigit = digits[index];
			digits[index] = digits[i];
			digits[i] = tmpDigit;
		}

		String returnStr = digits[0];
		for (int i = 1; i < size; i++) {
			returnStr = digits[i] + returnStr;
		}
		return returnStr;

	}

	// &quot;

	public static String filterHtml(String content) {
		content = content.replaceAll("'", "&quot");
		return content;
	}

	public static void main(String[] args) {
		System.err.println(MD5("123456"));
	}

	public static boolean isBefore10() {
		Calendar now = Calendar.getInstance();
		Calendar calendar = Calendar.getInstance();
		calendar.set(Calendar.HOUR_OF_DAY, 22);
		calendar.set(Calendar.MINUTE, 0);
		calendar.set(Calendar.SECOND, 0);
		if (now.after(calendar)) {
			return false;
		}
		return true;
	}

	public static String getPageData(int total, int pageSize, int start, String url) {
		String pageInfo = "";
		int pageCount = (int) Math.ceil((double) total / (double) pageSize);
		if (start > 1) {
			pageInfo += "<li class=\"prev\"><a style=\"height:29.2px;\" href=\"" + url + "&begin=" + (start - 1)
					+ "\"><i class=\"icon-double-angle-left\"></i></a></li>";
		} else {
			pageInfo += "<li class=\"prev disabled\"><a style=\"height:29.2px;\" href=\"javascript:void(0)\"><i class=\"icon-double-angle-left\"></i></a></li>";
		}
		int index = 1;
		if (start - 8 > 0) {
			index = start - 8;
		} else {
			index = 1;
		}
		int end = 0;
		if (start + 8 < pageCount) {
			end = start + 8;
		} else {
			end = pageCount;
		}
		for (int i = index; i <= end; i++) {
			pageInfo += "<li";
			if (i == start) {
				pageInfo += " class=\"active\"";
			}
			pageInfo += "><a href=\"" + url + "&begin=" + i + "\">" + i + "</a></li>";
		}
		if (start < pageCount) {
			pageInfo += "<li class=\"next\"><a href=\"" + url + "&begin=" + (start - 1)
					+ "\" style=\"height:29.2px;\"><i class=\"icon-double-angle-right\"></i></a></li>";
		} else {
			pageInfo += "<li class=\"next disabled\"><a href=\"javascript:void(0)\"   style=\"height:29.2px;\"><i class=\"icon-double-angle-right\"></i></a></li>";
		}
		return pageInfo;
	}

	public static String filter(String message) {
		if (message == null)
			return "";
		char content[] = new char[message.length()];
		message.getChars(0, message.length(), content, 0);
		StringBuffer result = new StringBuffer(content.length + 50);
		for (int i = 0; i < content.length; i++) {
			switch (content[i]) {
			case '<':
				result.append("&lt;");
				break;
			case '>':
				result.append("&gt;");
				break;
			case '&':
				result.append("&amp;");
				break;
			case '"':
				result.append("&quot;");
				break;
			default:
				result.append(content[i]);
			}
		}
		return (result.toString());

	}

    /**
     * 网络请求 get
     * @param url 请求地址
     * @return 请求响应
     * @throws IOException
     */
    public static String doHttpRequest(String url) throws IOException {
        URL localURL = new URL(url);
        URLConnection connection = localURL.openConnection();
        HttpURLConnection httpURLConnection = (HttpURLConnection)connection;

        httpURLConnection.setRequestProperty("Accept-Charset", "utf-8");
        httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        InputStream inputStream = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader reader = null;
        StringBuffer resultBuffer = new StringBuffer();
        String tempLine = null;

        if (httpURLConnection.getResponseCode() >= 300) {
//            throw new Exception("HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());
        }

        try {
            inputStream = httpURLConnection.getInputStream();
            inputStreamReader = new InputStreamReader(inputStream,"utf-8");
            reader = new BufferedReader(inputStreamReader);

            while ((tempLine = reader.readLine()) != null) {
                resultBuffer.append(tempLine);
            }
        } finally {

            if (reader != null) {
                reader.close();
            }

            if (inputStreamReader != null) {
                inputStreamReader.close();
            }

            if (inputStream != null) {
                inputStream.close();
            }

        }
        return resultBuffer.toString();
    }

	/**
	 * 签名生成算法
	 * @return 签名
	 * @throws IOException
	 */
	public static String getSignature(Map<String,String> params, String secret) throws IOException
	{
		// 先将参数以其参数名的字典序升序进行排序
		Map<String, String> sortedParams = new TreeMap<String, String>(params);
		Set<Map.Entry<String, String>> entrys = sortedParams.entrySet();

		// 遍历排序后的字典，将所有参数按"key=value"格式拼接在一起
		StringBuilder basestring = new StringBuilder();
		basestring.append(secret);
		for (Map.Entry<String, String> param : entrys) {
			basestring.append(param.getKey()).append(param.getValue());
		}
		basestring.append(secret);

		// 使用MD5对待签名串求签
		byte[] bytes = null;
		try {
			MessageDigest md5 = MessageDigest.getInstance("MD5");
			bytes = md5.digest(basestring.toString().getBytes());
		} catch (GeneralSecurityException ex) {
			throw new IOException(ex);
		}

		// 将MD5输出的二进制结果转换为小写的十六进制
		StringBuilder sign = new StringBuilder();
		for (int i = 0; i < bytes.length; i++) {
			String hex = Integer.toHexString(bytes[i] & 0xFF);
			if (hex.length() == 1) {
				sign.append("0");
			}
			sign.append(hex);
		}
		return sign.toString();
	}

	public static boolean isNeedUpdate(String netVersion, String localVersion) {
		if (!TextUtils.isEmpty(netVersion) && !TextUtils.isEmpty(localVersion)) {
			String[] netStr = netVersion.split("\\.");
			String[] localStr = localVersion.split("\\.");
			for (int i = 0; i < netStr.length; i++) {
				if (Integer.parseInt(netStr[i]) > Integer.parseInt(localStr[i])) {
					return true;
				} else if (Integer.parseInt(netStr[i]) < Integer
						.parseInt(localStr[i])) {
					return false;
				}
			}
		} else {
			return false;
		}
		return false;
	}




}
